"""
业务逻辑一致性验证器
Business Logic Consistency Validator

用于检查和修复IoT系统中的逻辑不一致问题
Used to check and fix logical inconsistencies in IoT systems
"""

import logging
import asyncio
from typing import Dict, Any, Optional, List, Tuple
from datetime import datetime, timedelta
from enum import Enum
import psutil
import threading

from config import IOT_CONFIG

logger = logging.getLogger(__name__)


class ValidationSeverity(Enum):
    """验证严重程度 / Validation severity levels"""
    INFO = "info"
    WARNING = "warning"
    ERROR = "error"
    CRITICAL = "critical"


class ValidationResult:
    """验证结果 / Validation result"""
    
    def __init__(self, rule_name: str, severity: ValidationSeverity, 
                 message: str, suggestions: List[str] = None):
        self.rule_name = rule_name
        self.severity = severity
        self.message = message
        self.suggestions = suggestions or []
        self.timestamp = datetime.now()


class LogicConsistencyValidator:
    """
    业务逻辑一致性验证器
    Business Logic Consistency Validator
    
    检查IoT系统中的逻辑一致性问题并提供修复建议
    Checks logical consistency issues in IoT systems and provides fix suggestions
    """
    
    def __init__(self):
        """初始化验证器 / Initialize validator"""
        self.logger = logging.getLogger(f"{self.__class__.__name__}")
        self.validation_results: List[ValidationResult] = []
        self._lock = threading.Lock()
        
        # 从配置文件获取阈值 / Get thresholds from config
        self.config = IOT_CONFIG
        
    def validate_timeout_consistency(self, components: Dict[str, Dict[str, Any]]) -> List[ValidationResult]:
        """
        验证超时配置一致性
        Validate timeout configuration consistency
        
        Args:
            components: 组件配置字典 / Component configuration dictionary
            
        Returns:
            List[ValidationResult]: 验证结果列表 / Validation results list
        """
        results = []
        
        try:
            # 收集所有超时配置 / Collect all timeout configurations
            timeouts = {}
            for component_name, config in components.items():
                for key, value in config.items():
                    if 'timeout' in key.lower():
                        timeouts[f"{component_name}.{key}"] = value
            
            # 检查超时配置的合理性 / Check timeout configuration reasonableness
            if timeouts:
                min_timeout = min(timeouts.values())
                max_timeout = max(timeouts.values())
                
                # 如果最大最小超时差异过大，提出警告 / Warn if timeout variance is too large
                if max_timeout > min_timeout * 10:
                    results.append(ValidationResult(
                        rule_name="timeout_variance_check",
                        severity=ValidationSeverity.WARNING,
                        message=f"超时配置差异过大 / Large timeout variance: {min_timeout}s - {max_timeout}s",
                        suggestions=[
                            "检查是否所有超时配置都合理 / Check if all timeout configurations are reasonable",
                            "考虑统一超时配置策略 / Consider unified timeout configuration strategy"
                        ]
                    ))
                
                # 检查是否有异常短的超时 / Check for abnormally short timeouts
                short_timeouts = [k for k, v in timeouts.items() if v < 5]
                if short_timeouts:
                    results.append(ValidationResult(
                        rule_name="short_timeout_check",
                        severity=ValidationSeverity.ERROR,
                        message=f"发现异常短的超时配置 / Found abnormally short timeouts: {short_timeouts}",
                        suggestions=[
                            "增加超时时间以避免频繁超时 / Increase timeout to avoid frequent timeouts",
                            "考虑业务处理的实际耗时 / Consider actual business processing time"
                        ]
                    ))
                
                # 检查是否有异常长的超时 / Check for abnormally long timeouts
                long_timeouts = [k for k, v in timeouts.items() if v > 300]  # 5分钟
                if long_timeouts:
                    results.append(ValidationResult(
                        rule_name="long_timeout_check",
                        severity=ValidationSeverity.WARNING,
                        message=f"发现异常长的超时配置 / Found abnormally long timeouts: {long_timeouts}",
                        suggestions=[
                            "检查是否需要如此长的超时时间 / Check if such long timeout is necessary",
                            "考虑添加进度反馈机制 / Consider adding progress feedback mechanism"
                        ]
                    ))
                    
        except Exception as e:
            results.append(ValidationResult(
                rule_name="timeout_validation_error",
                severity=ValidationSeverity.ERROR,
                message=f"超时验证失败 / Timeout validation failed: {str(e)}",
                suggestions=["检查配置文件格式 / Check configuration file format"]
            ))
            
        return results
    
    def validate_concurrency_limits(self, components: Dict[str, Dict[str, Any]]) -> List[ValidationResult]:
        """
        验证并发限制配置一致性
        Validate concurrency limit configuration consistency
        
        Args:
            components: 组件配置字典 / Component configuration dictionary
            
        Returns:
            List[ValidationResult]: 验证结果列表 / Validation results list
        """
        results = []
        
        try:
            # 收集并发配置 / Collect concurrency configurations
            concurrency_limits = {}
            for component_name, config in components.items():
                for key, value in config.items():
                    if any(word in key.lower() for word in ['concurrent', 'concurrency', 'parallel']):
                        concurrency_limits[f"{component_name}.{key}"] = value
            
            if concurrency_limits:
                # 获取系统CPU核心数 / Get system CPU core count
                cpu_count = psutil.cpu_count()
                total_concurrency = sum(concurrency_limits.values())
                
                # 检查总并发数是否过高 / Check if total concurrency is too high
                if total_concurrency > cpu_count * 20:  # 每核心最多20个并发
                    results.append(ValidationResult(
                        rule_name="excessive_concurrency_check",
                        severity=ValidationSeverity.WARNING,
                        message=f"总并发数过高 / Total concurrency too high: {total_concurrency} (CPU cores: {cpu_count})",
                        suggestions=[
                            f"建议总并发数不超过 {cpu_count * 10} / Recommend total concurrency not exceed {cpu_count * 10}",
                            "考虑系统资源限制 / Consider system resource limitations"
                        ]
                    ))
                
                # 检查并发配置是否合理 / Check if concurrency configuration is reasonable
                max_single_concurrency = max(concurrency_limits.values())
                if max_single_concurrency > cpu_count * 5:
                    results.append(ValidationResult(
                        rule_name="single_component_high_concurrency",
                        severity=ValidationSeverity.WARNING,
                        message=f"单组件并发数过高 / Single component concurrency too high: {max_single_concurrency}",
                        suggestions=[
                            f"建议单组件并发数不超过 {cpu_count * 2} / Recommend single component concurrency not exceed {cpu_count * 2}",
                            "使用队列和批处理优化性能 / Use queues and batch processing to optimize performance"
                        ]
                    ))
                    
        except Exception as e:
            results.append(ValidationResult(
                rule_name="concurrency_validation_error",
                severity=ValidationSeverity.ERROR,
                message=f"并发验证失败 / Concurrency validation failed: {str(e)}",
                suggestions=["检查系统资源信息获取 / Check system resource information retrieval"]
            ))
            
        return results
    
    def validate_error_handling_consistency(self, device_handlers: Dict[str, Any]) -> List[ValidationResult]:
        """
        验证错误处理一致性
        Validate error handling consistency
        
        Args:
            device_handlers: 设备处理器字典 / Device handlers dictionary
            
        Returns:
            List[ValidationResult]: 验证结果列表 / Validation results list
        """
        results = []
        
        try:
            # 检查异常处理策略一致性 / Check exception handling strategy consistency
            l16_errors_handled = []
            s8_errors_handled = []
            
            # 模拟检查不同设备类型的错误处理方式 / Simulate checking error handling methods for different device types
            # 这里应该通过代码分析来实现，简化为配置检查
            # This should be implemented through code analysis, simplified to configuration check
            
            error_config = self.config.get('error_handling', {})
            max_retries = error_config.get('max_retries', 3)
            retry_delay = error_config.get('retry_delay', 1.0)
            
            if max_retries > 10:
                results.append(ValidationResult(
                    rule_name="excessive_retry_count",
                    severity=ValidationSeverity.WARNING,
                    message=f"重试次数过多可能导致性能问题 / Excessive retry count may cause performance issues: {max_retries}",
                    suggestions=[
                        "建议重试次数不超过5次 / Recommend retry count not exceed 5",
                        "考虑使用断路器模式 / Consider using circuit breaker pattern"
                    ]
                ))
            
            if retry_delay > 10.0:
                results.append(ValidationResult(
                    rule_name="long_retry_delay",
                    severity=ValidationSeverity.WARNING,
                    message=f"重试延迟过长可能影响用户体验 / Long retry delay may affect user experience: {retry_delay}s",
                    suggestions=[
                        "考虑使用指数退避策略 / Consider using exponential backoff strategy",
                        "优化错误恢复逻辑 / Optimize error recovery logic"
                    ]
                ))
                
        except Exception as e:
            results.append(ValidationResult(
                rule_name="error_handling_validation_error",
                severity=ValidationSeverity.ERROR,
                message=f"错误处理验证失败 / Error handling validation failed: {str(e)}",
                suggestions=["检查错误处理配置 / Check error handling configuration"]
            ))
            
        return results
    
    def validate_data_validation_logic(self, validation_config: Dict[str, Any]) -> List[ValidationResult]:
        """
        验证数据验证逻辑一致性
        Validate data validation logic consistency
        
        Args:
            validation_config: 验证配置 / Validation configuration
            
        Returns:
            List[ValidationResult]: 验证结果列表 / Validation results list
        """
        results = []
        
        try:
            strict_validation = validation_config.get('strict_validation', False)
            confidence_threshold = validation_config.get('data_confidence_threshold', 0.7)
            required_fields_check = validation_config.get('required_fields_check', True)
            
            # 检查置信度阈值合理性 / Check confidence threshold reasonableness
            if confidence_threshold < 0.5:
                results.append(ValidationResult(
                    rule_name="low_confidence_threshold",
                    severity=ValidationSeverity.WARNING,
                    message=f"数据置信度阈值过低 / Data confidence threshold too low: {confidence_threshold}",
                    suggestions=[
                        "建议置信度阈值至少为0.6 / Recommend confidence threshold at least 0.6",
                        "评估数据质量要求 / Evaluate data quality requirements"
                    ]
                ))
            
            if confidence_threshold > 0.95:
                results.append(ValidationResult(
                    rule_name="high_confidence_threshold",
                    severity=ValidationSeverity.INFO,
                    message=f"数据置信度阈值很高 / Data confidence threshold very high: {confidence_threshold}",
                    suggestions=[
                        "确保数据源质量足够高 / Ensure data source quality is high enough",
                        "可能需要更多的数据预处理 / May need more data preprocessing"
                    ]
                ))
            
            # 检查严格验证模式与性能的平衡 / Check balance between strict validation mode and performance
            if strict_validation and not required_fields_check:
                results.append(ValidationResult(
                    rule_name="validation_logic_inconsistency",
                    severity=ValidationSeverity.WARNING,
                    message="启用严格验证但禁用必填字段检查 / Strict validation enabled but required fields check disabled",
                    suggestions=[
                        "建议同时启用必填字段检查 / Recommend enabling required fields check",
                        "检查验证配置逻辑 / Check validation configuration logic"
                    ]
                ))
                
        except Exception as e:
            results.append(ValidationResult(
                rule_name="data_validation_logic_error",
                severity=ValidationSeverity.ERROR,
                message=f"数据验证逻辑检查失败 / Data validation logic check failed: {str(e)}",
                suggestions=["检查验证配置格式 / Check validation configuration format"]
            ))
            
        return results
    
    def validate_resource_management(self) -> List[ValidationResult]:
        """
        验证资源管理策略
        Validate resource management strategy
        
        Returns:
            List[ValidationResult]: 验证结果列表 / Validation results list
        """
        results = []
        
        try:
            # 获取系统资源信息 / Get system resource information
            memory_info = psutil.virtual_memory()
            available_memory_mb = memory_info.available // (1024 * 1024)
            
            # 检查内存限制配置 / Check memory limit configuration
            memory_limit = self.config.get('logging', {}).get('memory_limit_mb', 512)
            
            if memory_limit > available_memory_mb * 0.8:
                results.append(ValidationResult(
                    rule_name="excessive_memory_limit",
                    severity=ValidationSeverity.ERROR,
                    message=f"内存限制过高 / Memory limit too high: {memory_limit}MB (Available: {available_memory_mb}MB)",
                    suggestions=[
                        f"建议内存限制不超过 {int(available_memory_mb * 0.5)}MB / Recommend memory limit not exceed {int(available_memory_mb * 0.5)}MB",
                        "考虑系统其他进程的内存需求 / Consider memory requirements of other system processes"
                    ]
                ))
            
            if memory_limit < 128:
                results.append(ValidationResult(
                    rule_name="insufficient_memory_limit",
                    severity=ValidationSeverity.WARNING,
                    message=f"内存限制可能不足 / Memory limit may be insufficient: {memory_limit}MB",
                    suggestions=[
                        "考虑增加内存限制以提高性能 / Consider increasing memory limit for better performance",
                        "监控实际内存使用情况 / Monitor actual memory usage"
                    ]
                ))
            
            # 检查设备数量限制 / Check device count limit
            max_devices = self.config.get('device_monitoring', {}).get('max_devices', 10000)
            estimated_memory_per_device = 50  # KB per device
            total_estimated_memory = (max_devices * estimated_memory_per_device) // 1024  # MB
            
            if total_estimated_memory > memory_limit:
                results.append(ValidationResult(
                    rule_name="device_count_memory_mismatch",
                    severity=ValidationSeverity.WARNING,
                    message=f"设备数量限制与内存限制不匹配 / Device count limit mismatched with memory limit: {max_devices} devices may use {total_estimated_memory}MB",
                    suggestions=[
                        f"考虑将设备数量限制到 {(memory_limit * 1024) // estimated_memory_per_device} / Consider limiting device count to {(memory_limit * 1024) // estimated_memory_per_device}",
                        "优化设备数据存储结构 / Optimize device data storage structure"
                    ]
                ))
                
        except Exception as e:
            results.append(ValidationResult(
                rule_name="resource_management_validation_error",
                severity=ValidationSeverity.ERROR,
                message=f"资源管理验证失败 / Resource management validation failed: {str(e)}",
                suggestions=["检查系统资源信息 / Check system resource information"]
            ))
            
        return results
    
    async def run_comprehensive_validation(self) -> Dict[str, List[ValidationResult]]:
        """
        运行综合验证
        Run comprehensive validation
        
        Returns:
            Dict[str, List[ValidationResult]]: 分类的验证结果 / Categorized validation results
        """
        try:
            self.logger.info("开始业务逻辑一致性验证 / Starting business logic consistency validation")
            
            all_results = {
                'timeout_consistency': [],
                'concurrency_limits': [],
                'error_handling': [],
                'data_validation': [],
                'resource_management': []
            }
            
            # 超时一致性验证 / Timeout consistency validation
            timeout_components = {
                'data_processing': self.config.get('data_processing', {}),
                'command_handling': self.config.get('command_handling', {}),
                'device_monitoring': self.config.get('device_monitoring', {})
            }
            all_results['timeout_consistency'] = self.validate_timeout_consistency(timeout_components)
            
            # 并发限制验证 / Concurrency limits validation
            concurrency_components = {
                'data_processing': self.config.get('data_processing', {}),
                'command_handling': self.config.get('command_handling', {}),
                'device_monitoring': self.config.get('device_monitoring', {})
            }
            all_results['concurrency_limits'] = self.validate_concurrency_limits(concurrency_components)
            
            # 错误处理验证 / Error handling validation
            all_results['error_handling'] = self.validate_error_handling_consistency({})
            
            # 数据验证逻辑验证 / Data validation logic validation
            validation_config = self.config.get('validation', {})
            all_results['data_validation'] = self.validate_data_validation_logic(validation_config)
            
            # 资源管理验证 / Resource management validation
            all_results['resource_management'] = self.validate_resource_management()
            
            # 统计验证结果 / Count validation results
            total_issues = sum(len(results) for results in all_results.values())
            critical_issues = sum(1 for results in all_results.values() 
                                for result in results if result.severity == ValidationSeverity.CRITICAL)
            error_issues = sum(1 for results in all_results.values() 
                             for result in results if result.severity == ValidationSeverity.ERROR)
            
            self.logger.info(
                f"业务逻辑验证完成 / Business logic validation completed: "
                f"总问题数 / Total issues: {total_issues}, "
                f"严重问题 / Critical: {critical_issues}, "
                f"错误 / Errors: {error_issues}"
            )
            
            return all_results
            
        except Exception as e:
            self.logger.error(f"综合验证失败 / Comprehensive validation failed: {str(e)}")
            return {}
    
    def generate_validation_report(self, validation_results: Dict[str, List[ValidationResult]]) -> str:
        """
        生成验证报告
        Generate validation report
        
        Args:
            validation_results: 验证结果 / Validation results
            
        Returns:
            str: 验证报告 / Validation report
        """
        try:
            report_lines = [
                "="*80,
                "IoT系统业务逻辑一致性验证报告 / IoT System Business Logic Consistency Validation Report",
                "="*80,
                f"生成时间 / Generated at: {datetime.now().isoformat()}",
                ""
            ]
            
            total_issues = 0
            for category, results in validation_results.items():
                if not results:
                    continue
                    
                total_issues += len(results)
                report_lines.extend([
                    f"\n{category.upper().replace('_', ' ')} ({len(results)} issues):",
                    "-" * 60
                ])
                
                for result in results:
                    report_lines.extend([
                        f"[{result.severity.value.upper()}] {result.rule_name}",
                        f"  消息 / Message: {result.message}",
                        f"  时间 / Time: {result.timestamp.isoformat()}"
                    ])
                    
                    if result.suggestions:
                        report_lines.append("  建议 / Suggestions:")
                        for suggestion in result.suggestions:
                            report_lines.append(f"    - {suggestion}")
                    report_lines.append("")
            
            if total_issues == 0:
                report_lines.extend([
                    "\n✅ 未发现业务逻辑一致性问题 / No business logic consistency issues found",
                    "系统配置看起来是一致的 / System configuration appears to be consistent"
                ])
            else:
                report_lines.extend([
                    f"\n📊 总结 / Summary:",
                    f"发现 {total_issues} 个问题需要关注 / Found {total_issues} issues that need attention",
                    "建议按照优先级修复这些问题 / Recommend fixing these issues by priority"
                ])
            
            report_lines.extend([
                "",
                "="*80
            ])
            
            return "\n".join(report_lines)
            
        except Exception as e:
            return f"生成验证报告失败 / Failed to generate validation report: {str(e)}"


# 全局验证器实例 / Global validator instance
logic_validator = LogicConsistencyValidator()


async def validate_business_logic() -> str:
    """
    验证业务逻辑一致性的便捷函数
    Convenience function to validate business logic consistency
    
    Returns:
        str: 验证报告 / Validation report
    """
    try:
        results = await logic_validator.run_comprehensive_validation()
        return logic_validator.generate_validation_report(results)
    except Exception as e:
        logger.error(f"业务逻辑验证失败 / Business logic validation failed: {str(e)}")
        return f"验证失败 / Validation failed: {str(e)}"


if __name__ == "__main__":
    # 测试验证器 / Test validator
    async def main():
        report = await validate_business_logic()
        print(report)
    
    asyncio.run(main())